/**
 * @file ext-helloworld.js
 *
 * @license MIT
 *
 * @copyright 2010 Alexis Deveria
 *
 */
const name = 'cube'

const loadExtensionTranslation = async function (svgEditor) {
  let translationModule
  const lang = svgEditor.configObj.pref('lang')
  try {
    translationModule = await import(`./locale/${lang}.js`)
  } catch (_error) {
    console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
    translationModule = await import('./locale/en.js')
  }
  svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
}

export default {
  name,
  async init({
    _importLocale
  }) {
    const svgEditor = this
    await loadExtensionTranslation(svgEditor)

    const {
      svgCanvas
    } = svgEditor
    const {
      $id,
      $qq,
      $
    } = svgCanvas

    const modeId = 'cube'
    const startClientPos = {}

    let curShape
    let startX
    let startY

    let curtId
    let lastBBox = {}
    let _data

    return {
      //我有哦不可忽视的观看距离
      name: svgEditor.i18next.t(`${name}:name`),
      async callback () {
        const response = await fetch(`oldImg/cube.svg`)
        _data = await response.text();

        const buttonTemplate = `<se-button id="tool_cube" title="tools.cube" src="cube.svg" class='cube'></se-button>`
        svgCanvas.insertChildAtIndex($qq('.basicWrap .itemWrap'), buttonTemplate, 8)


        const onClickHandler = (ev) => {
          ev.stopPropagation()
          this.currentAction = ev.target
          curtId = this.currentAction.id
          // 修改选中焦点
          if (this.leftPanel.updateLeftPanel(curtId)) {
            svgCanvas.setMode(modeId)
          }
        }

        svgEditor.$click($id('tool_cube'), onClickHandler)
      },
      // This is triggered when the main mouse button is pressed down
      // on the editor canvas (not the tool panels)
      mouseDown(opts) {
        const mode = svgCanvas.getMode()
        if (mode !== modeId) { return undefined }
        // The returned object must include "started" with
        // a value of true in order for mouseUp to be triggered
        startX = opts.start_x
        const x = startX
        startY = opts.start_y
        const y = startY

        startClientPos.x = opts.event.clientX
        startClientPos.y = opts.event.clientY

        const curContent =_data;
        const curStyle = svgCanvas.getStyle()

        let addGElement = (curShape, element) => {
          let children = $(element).find("g>*");
          $(children).each(function () {
            let tagName = this.tagName;
            if (tagName == 'g') {
              addGElement(curShape , this);
            } else {
              let newElement = $(this).clone().attr({
                "id": svgCanvas.getNextId(),
                "stroke-width": 1
              });
              $(curShape).append(newElement);
              if (tagName == "path") {
                let path = newElement[0]
                const d = newElement.attr("d");
                if (/[a-z]/.test(d)) {
                  const convertedPath = svgCanvas.pathActions.convertPath(path);
                  path.setAttribute('d', convertedPath);
                  svgCanvas.pathActions.fixEnd(path);
                }
                svgCanvas.recalculateDimensions(path);
              }
            }
          });
        };

        let elements = $(curContent).find("g>*");
        let elementLength = $(curContent).find("g>path").length;
        if (elements.length > 1 || elementLength != elements.length) {
          curShape = svgCanvas.addSVGElementsFromJson({
            "element": "g",
            "curStyles": true,
            "attr": {
              "id": svgCanvas.getNextId(),
              "doc-type":'cube',
              'class': 'cube'
            }
          });
          addGElement(curShape, curContent);
        } else {
          let currentD = $(curContent).find('path').attr("d");
          curShape = svgCanvas.addSVGElementsFromJson({
            "element": "path",
            "curStyles": true,
            "attr": {
              "d": currentD,
              "id": svgCanvas.getNextId(),
              "opacity": curStyle.opacity / 2,
              "style": "pointer-events:none",
              // "docType": curType.replace("tool_", ""),
              "stroke-width": 2,
              // "fill": $(curContent).attr("fill"),
              // "stroke": $(curContent).attr("stroke"),
              'class': 'ems'
            }
          });
          // Make sure shape uses absolute values
          if (/[a-z]/.test(currentD)) {
            currentD = svgCanvas.pathActions.convertPath(curShape);
            curShape.setAttribute('d', currentD);
            svgCanvas.pathActions.fixEnd(curShape);
          }
        }

        curShape.setAttribute('transform', 'translate(' + x + ',' + y + ') scale(0.005) translate(' + -x + ',' + -y + ')')

        svgCanvas.recalculateDimensions(curShape);

        lastBBox = curShape.getBBox();
        return {
          started: true
        };
      },
      mouseMove: function (opts) {
        const mode = svgCanvas.getMode()
        if (mode !== modeId) {
          return
        }

        const zoom = svgCanvas.getZoom()
        const evt = opts.event

        const x = opts.mouse_x / zoom
        const y = opts.mouse_y / zoom

        const tlist = curShape.transform.baseVal
        const box = curShape.getBBox()
        const left = box.x;
        const top = box.y

        const newBox = {
          x: Math.min(startX, x),
          y: Math.min(startY, y),
          width: Math.abs(x - startX),
          height: Math.abs(y - startY)
        }

        let sx = (newBox.width / lastBBox.width) || 1
        let sy = (newBox.height / lastBBox.height) || 1

        // Not perfect, but mostly works...
        let tx = 0
        if (x < startX) {
          tx = lastBBox.width
        }
        let ty = 0
        if (y < startY) {
          ty = lastBBox.height
        }

        // update the transform list with translate,scale,translate
        const translateOrigin = svgroot.createSVGTransform()
        const scale = svgroot.createSVGTransform()
        const translateBack = svgroot.createSVGTransform()

        translateOrigin.setTranslate(-(left + tx), -(top + ty))
        if (!evt.shiftKey) {
          const max = Math.min(Math.abs(sx), Math.abs(sy))

          sx = max * (sx < 0 ? -1 : 1)
          sy = max * (sy < 0 ? -1 : 1)
        }
        scale.setScale(sx, sy)

        translateBack.setTranslate(left + tx, top + ty)
        tlist.appendItem(translateBack)
        tlist.appendItem(scale)
        tlist.appendItem(translateOrigin)

        svgCanvas.recalculateDimensions(curShape)

        lastBBox = curShape.getBBox()
      },
      // This is triggered from anywhere, but "started" must have been set
      // to true (see above). Note that "opts" is an object with event info
      mouseUp(opts) {
        const mode = svgCanvas.getMode()
        if (mode !== modeId) {
          return undefined
        }
        // svgCanvas.setMode('select')

        const keepObject = (opts.event.clientX !== startClientPos.x && opts.event.clientY !== startClientPos.y)

        return {
          keep: keepObject,
          element: curShape,
          started: false
        }
      },
      updateCube(val){
        if(val.mode !== modeId){
          return 
        }
        const elem = svgCanvas.getSelectedElements()[0]
        var opts = val.data
        if (elem) {
            var selectedElements2 = $(elem);
            var  children = selectedElements2.children();
            var  firstChild = children.eq(0)
            var  secondChild = children.eq(1)
            var  threeChild = children.eq(2)
            
            firstChild[0].setAttribute("fill",opts[0]);
            secondChild[0].setAttribute("fill",opts[1]);
            threeChild[0].setAttribute("fill",opts[2]);
            if(elem.classList[1]){
              elem.classList.remove(elem.classList[1])
            }
        }
      }
    }
  }
}
